package com.hcb.tonguetiphealth.widget.homepage;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.ChatActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class HomepageMemberWidget extends GeneralWidget implements OnClickListener {
	
	private Activity ctx;

	private Handler mHandler;
	private TextView tvUserName, tvSex, tvLabels, tvInfo, tvArea, tv_height, tv_weight;
	private RatingBar rbLevel;
	private Button  btFans, btAttention, bt_newMessage;
	private User user;
	private ImageView imgUser;
	private String fromWidgetFlag;
	private LinearLayout llAttentoin;
	
//	private ImageView imgUporDown;
//	private ImageView infoImgUporDown;
	
//	private LinearLayout llLabels, llInfo ;
	private LinearLayout llBack;
	private boolean requestSuccess;
	private String fromWidget;
	
	public HomepageMemberWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.homepage_member_info, this); 
		//db = DBManager.getInstance(ctx);
		Bundle bundle = ctx.getIntent().getExtras();
		user = (User)bundle.get("memeber");
		fromWidget = ctx.getIntent().getStringExtra("fromWidget");
		System.out.println("user"+user);
	//	fromWidgetFlag = ctx.getIntent().getStringExtra("fromWidgetFlag");
		//new BottomWidget(ctx, this);
		bindView();
		bindEvent();
		initData();
		if ("CityWideActivitysListAdapter".equals(fromWidget)
				|| "HealthShareListAdapter".equals(fromWidget)
				|| "HealthShareInfoWidget".equals(fromWidget)) {
			getUserInfo();
		}
	}
	
	private void bindView(){
		//底部按钮
 
		tvUserName = (TextView)findViewById(R.id.homepage_personal_textview);
		tvSex = (TextView)findViewById(R.id.homepage_personal_sex_textview);
		tvArea = (TextView)findViewById(R.id.homepage_personal_area_textview);
		tvLabels =(TextView)findViewById(R.id.homepage_personal_labes_textview);
		tvInfo = (TextView)findViewById(R.id.homepage_personal_info_textview);
		tv_height = (TextView)findViewById(R.id.homepage_personal_height_textview);
		tv_weight = (TextView)findViewById(R.id.homepage_personal_weight_textview);
		rbLevel = (RatingBar)findViewById(R.id.homepage_personal_info_ratingbar);
		imgUser = (ImageView)findViewById(R.id.homepage_personal_img);
 
		btFans = (Button)findViewById(R.id.homepage_member_fans_bt);
		btAttention = (Button)findViewById(R.id.homepage_member_attention_bt);
		bt_newMessage = (Button)findViewById(R.id.homepage_personal_new_message_bt);
		
		llBack = (LinearLayout)findViewById(R.id.homepage_member_back);
		llAttentoin = (LinearLayout)findViewById(R.id.member_attention);
//		llLabels = (LinearLayout)findViewById(R.id.homepage_member_labels_linearlayout);
//		llInfo = (LinearLayout)findViewById(R.id.homepage_member_info_linearlayout);
		
//		imgUporDown = (ImageView)findViewById(R.id.res_book_res_content_upordown);
//		infoImgUporDown = (ImageView)findViewById(R.id.member_info_upordown);
	}
	
	private void bindEvent(){
 
//		btBack.setOnClickListener(this);
		btFans.setOnClickListener(this);
		btAttention.setOnClickListener(this);
		bt_newMessage.setOnClickListener(this);
		llBack.setOnClickListener(this);
		llAttentoin.setOnClickListener(this);
//		llLabels.setOnClickListener(this);
//		llInfo.setOnClickListener(this);
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在发送请求...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					if (requestSuccess) {
						showMessage(ctx, "关注成功！");
					}else {
						showMessage(ctx, "请求失败，请稍后重试");
					}
					dismissMessageDialog();
				case MessageWhat.DIMISS_DIALOG_LOADED:
					initData();
					dismissMessageDialog();
					break;
				default:
					break;
				}
			}
			
		};
	}
	
	private void getUserInfo(){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				System.out.println("参数userid"+user.getUserId());
				params.add(new BasicNameValuePair("userId", user.getUserId()));
				String response = HttpUtils.Post(Global.getServletUserinfo(), params);
				if (Global.DEBUG) {
					System.out.println("用户信息返回结果："+response);
					
				}
				if(response!=null){
					try {
							JSONObject obj = new JSONObject(response);
							JSONObject jsonObject = (JSONObject)obj.getJSONObject("result");
							// System.out.println(strReturn+"sucess");
							user.setUserId(jsonObject.getString("userid"));
							user.setUserName(jsonObject.getString("username"));
							user.setImgUrl(jsonObject.getString("headicon"));
							user.setSex(jsonObject.getString("gender"));
							
							user.setBirthDayTimeInMillis(1000*StringUtils.parseLong(jsonObject.getString("birthday")));
							user.setHeight(jsonObject.getString("height"));
							user.setWeight(jsonObject.getString("weight"));
							user.setCheckedBody(jsonObject.getString("physical"));
							
							user.setLabels(jsonObject.getString("tags"));
							user.setInfo(jsonObject.getString("intro"));
							user.setLevel(StringUtils.parseFloat(jsonObject.getString("level")));
							user.setProvince(jsonObject.getString("province"));
							user.setCity(jsonObject.getString("city"));
							user.seteMail(jsonObject.getString("email"));
							user.setRealName(jsonObject.getString("truename"));
							user.setTel(jsonObject.getString("mobile"));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG_LOADED);
			}
		}.start();
		
	}
	
	private void initData(){
		if (user!=null) {
			tvUserName.setText(user.getUserName());
			String sex = "男";
			if (("1").equals(user.getSex())) {
				sex = "男";
			}else if("2".equals(user.getSex())){
				sex = "女";
			}
			tvSex.setText(sex);
			tvArea.setText( user.getAge() + " 岁");
			tv_height.setText(user.getHeight().equals("null")?"cm":user.getHeight() + "cm");
			tv_weight.setText(user.getWeight().equals("null")?"kg":user.getWeight() + "kg");  
			//tvArea.setText(user.getArea());
			tvLabels.setText(user.getLabels());
			tvInfo.setText(user.getInfo());
			rbLevel.setRating(user.getLevel());
			loadImage(imgUser, user.getImgUrl());
		}
		
	}
	
	
	/**
	 * 底部功能菜单按钮点击事件
	 */
	public void onClick(View v) {
		Intent intent = new Intent();
		switch(v.getId()) {
 
		case R.id.homepage_member_fans_bt:
			Bundle bundle = new Bundle();
			bundle.putSerializable("user", user);
			ctx.getIntent().putExtras(bundle);
			ctx.getIntent().putExtra("type", "1");
			ctx.getIntent().putExtra("FromWidgetFlag", "HomepageMemberWidget");
			ctx.setContentView(new FansAttentionListWidget(ctx));
			break;
		case R.id.homepage_member_attention_bt:
			bundle = new Bundle();
			bundle.putSerializable("user", user);
			ctx.getIntent().putExtras(bundle);
			ctx.getIntent().putExtra("type", "2");
			ctx.getIntent().putExtra("FromWidgetFlag", "HomepageMemberWidget");
			ctx.setContentView(new FansAttentionListWidget(ctx));
			break;
		case R.id.homepage_personal_new_message_bt:
			if(Global.user == null) {
				showMessage(ctx, "请登录!");
				login();
			} else if(Global.user.getUserName().equals(user.getUserName())) {
				showMessage(ctx, "不可与自己私信互动");
			} else {
				intent.setClass(ctx, ChatActivity.class);
				intent.putExtra("user", user);
				intent.putExtra("from", "user");
				ctx.startActivity(intent);
			}
			break;
		case R.id.homepage_member_back:
			ctx.finish();
			break;
		case R.id.member_attention:
			atentionMember();
			break;
//		case R.id.homepage_member_labels_linearlayout:
//			if(tvLabels.getVisibility() == View.GONE || tvLabels.getVisibility() == View.INVISIBLE){
//				tvLabels.setVisibility(View.VISIBLE);
//				imgUporDown.setBackgroundResource(R.drawable.close_more);
//			}else {
//				tvLabels.setVisibility(View.GONE);
//				imgUporDown.setBackgroundResource(R.drawable.open_more);
//			}
//			break;
//		case R.id.homepage_member_info_linearlayout:
//			if(tvInfo.getVisibility() == View.GONE || tvInfo.getVisibility() == View.INVISIBLE){
//				tvInfo.setVisibility(View.VISIBLE);
//				infoImgUporDown.setBackgroundResource(R.drawable.close_more);
//			}else {
//				tvInfo.setVisibility(View.GONE);
//				infoImgUporDown.setBackgroundResource(R.drawable.open_more);
//			}
//			break;
		default:
			break;
		}
	}
	
	private void atentionMember(){
		if (Global.user == null) {
			showMessage(ctx, "请登录!");
			login();
		}else {
			mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
			requestSuccess = false;
			new Thread(){
				public void run() {
					List<NameValuePair>params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("memberUserId", user.getUserId()));
					params.add(new BasicNameValuePair("myUserid", Global.user.getUserId()));
					String response = HttpUtils.Post(Global.getServletattentoin(), params);
					if (response!=null) {
						try {
							JSONObject jsonObject = new JSONObject(response);
							String strReturn = jsonObject.getString("return");
							if ("true".equals(strReturn)) {
								requestSuccess = true;
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} 
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}
			}.start();
		}
		
	}
	
	@Override
	public void notifyAdapter() {
		
	}
 
}
